﻿const Book = require("../models/book");
const Category = require("../models/category");
const logger = require("../config/logger");

exports.getBooks = async (ctx) => {
  const books = await Book.findAll({ include: Category });
  // const books = await Book.findAll();

  ctx.body = { code: 200, message: "查询图书列表成功", data: books };
};

exports.getBookById = async (ctx) => {
  logger.info(`要查询图书的ID：${ctx.params.bookId}`);

  const book = await Book.findAll({
    where: { bookId: ctx.params.bookId },
    include: Category,
  });

  ctx.body = { code: 200, message: "查询图书成功", data: book };
};

exports.addBook = async (ctx) => {
  logger.info(`要添加的图书信息：${ctx.request.body}`);

  const { bookName, categoryId, author, description } = ctx.request.body;

  const newBook = Book.create({ bookName, categoryId, author, description });

  ctx.body = { code: 200, message: "添加图书成功", data: null };
};

exports.deleteBook = async (ctx) => {
  const bookId = ctx.params.bookId;

  logger.info(`要删除的图书 ID: ${bookId}`);

  await Book.destroy({
    where: {
      bookId,
    },
  });

  ctx.body = { code: 200, message: "删除图书成功", data: null };
};

exports.updateBook = async (ctx) => {
  logger.info("要修改的图书信息：\n", ctx.request.body);

  const { bookId, bookName, author, categoryId, description } =
    ctx.request.body;

  await Book.update(
    { bookName, author, categoryId, description },
    { where: { bookId } },
  );

  ctx.body = { code: 200, message: "修改图书成功", data: null };
};
